package apis

import (
	"fmt"
	log "github.com/go-admin-team/go-admin-core/logger"
	"github.com/gorilla/websocket"
	"net/http"
	"sync"
	"vrcm/src/vrcm/common/apis"

	"github.com/gin-gonic/gin"

	_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"

	"vrcm/src/vrcm/app/admin/models/live_schedule"
	"vrcm/src/vrcm/app/admin/service/dto/live_schedule"
	"vrcm/src/vrcm/app/admin/service/live_schedule"
	"vrcm/src/vrcm/common/actions"
)

type ChannelTask struct {
	apis.Api
}

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// GetPage 获取ChannelTask列表
// @Summary 获取ChannelTask列表
// @Description 获取ChannelTask列表
// @Tags ChannelTask
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response{data=response.Page{list=[]models.ChannelTaskService}} "{"code": 200, "data": [...]}"
// @Router /api/v1/channel-task [get]
// @Security Bearer
func (e ChannelTask) GetPage(c *gin.Context) {
	req := dto.ChannelTaskGetPageReq{}
	s := service.ChannelTaskService{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	p := actions.GetPermissionFromContext(c)
	list := make([]live_schedule.ChannelTask, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取通道失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Get 获取ChannelTask
// @Summary 获取ChannelTask
// @Description 获取ChannelTask
// @Tags ChannelTask
// @Param id path int false "id"
// @Success 200 {object} response.Response{data=models.ChannelTaskService} "{"code": 200, "data": [...]}"
// @Router /api/v1/channel-task/{id} [get]
// @Security Bearer
func (e ChannelTask) Get(c *gin.Context) {
	req := dto.ChannelTaskGetReq{}
	s := service.ChannelTaskService{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	err = s.Get(&req)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取通道失败， %s", err.Error()))
		return
	}

	e.OK("object", "查询成功")
}

// Insert 创建ChannelTask
// @Summary 创建ChannelTask
// @Description 创建ChannelTask
// @Tags ChannelTask
// @Accept application/json
// @Product application/json
// @Param data body dto.ChannelTaskInsertReq true "data"
// @Success 200 {object} response.Response	"{"code": 200, "message": "添加成功"}"
// @Router /api/v1/channel-task [post]
// @Security Bearer
func (e ChannelTask) Insert(c *gin.Context) {
	req := dto.ChannelTaskInsertReq{}
	s := service.ChannelTaskService{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	err = s.Insert(&req)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("创建通道失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.OK(req.GetId(), "创建成功")
}

// Update 修改ChannelTask
// @Summary 修改ChannelTask
// @Description 修改ChannelTask
// @Tags ChannelTask
// @Accept application/json
// @Product application/json
// @Param id path int true "id"
// @Param data body dto.ChannelTaskUpdateReq true "body"
// @Success 200 {object} response.Response	"{"code": 200, "message": "修改成功"}"
// @Router /api/v1/channel-task/{id} [put]
// @Security Bearer
func (e ChannelTask) Update(c *gin.Context) {
	req := dto.ChannelTaskUpdateReq{}
	s := service.ChannelTaskService{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	p := actions.GetPermissionFromContext(c)

	err = s.Update(&req, p)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("修改通道k失败， %s", err.Error()))
		return
	}
	e.OK(req.GetId(), "修改成功")
}

// Delete 删除ChannelTask
// @Summary 删除ChannelTask
// @Description 删除ChannelTask
// @Tags ChannelTask
// @Param data body dto.ChannelTaskDeleteReq true "body"
// @Success 200 {object} response.Response	"{"code": 200, "message": "删除成功"}"
// @Router /api/v1/channel-task [delete]
// @Security Bearer
func (e ChannelTask) Delete(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.ChannelTaskDeleteReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	// req.SetUpdateBy(user.GetUserId(c))
	p := actions.GetPermissionFromContext(c)

	err = s.Remove(&req, p)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("删除通道失败， %s", err.Error()))
		return
	}
	e.OK(req.GetId(), "删除成功")
}

func (e ChannelTask) SaveTrafficOn(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.TrafficOnSaveReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.SaveTrafficOn(&req)
	if err != nil {
		e.Error(apis.SaveTrafficOnError.Code, err, fmt.Sprintf("保存上车点失败， %s", err.Error()))
		return
	}
	info := dto.NodeInfo{
		Id:     req.Id,
		NodeId: req.NodeId,
	}
	e.OK(info, "保存上车点成功")
}

func (e ChannelTask) SaveTrafficOns(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.TrafficOnsSaveReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	data, err := s.SaveTrafficOns(&req)
	if err != nil {
		e.Error(apis.SaveTrafficOnError.Code, err, fmt.Sprintf("保存上车点失败， %s", err.Error()))
		return
	}
	e.OK(data, "保存上车点成功")
}

func (e ChannelTask) GetTrafficOn(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.TrafficOnGetReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	var count int64
	data, err := s.GetTrafficOn(&req, &count)
	if err != nil {
		e.Error(apis.DBQueryError.Code, err, fmt.Sprintf("获取上车点失败， %s", err.Error()))
		return
	}
	//c.Writer.Header().Set("Content-Length", "-1")
	e.PageOK(data, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

func (e ChannelTask) GetTrafficOns(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.TrafficOnGetReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	var count int64
	data, err := s.GetTrafficOns(&req, &count)
	if err != nil {
		e.Error(apis.DBQueryError.Code, err, fmt.Sprintf("获取上车点失败， %s", err.Error()))
		return
	}
	e.PageOK(data, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

func (e ChannelTask) RemoveTrafficOn(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.TrafficOnDeleteReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.RemoveTrafficOn(&req)
	if err != nil {
		e.Error(apis.DeleteTrafficOnError.Code, err, fmt.Sprintf("删除上车点失败， %s", err.Error()))
		return
	}
	e.OK("", "删除成功")
}

func (e ChannelTask) RemoveTrafficOns(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.TrafficOnDeleteReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.RemoveTrafficOns(&req)
	if err != nil {
		e.Error(apis.DeleteTrafficOnError.Code, err, fmt.Sprintf("删除上车点失败， %s", err.Error()))
		return
	}
	e.OK("", "删除成功")
}

func (e ChannelTask) SaveMediaProcess(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.MediaProcessSaveReq1{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.SaveMediaProcess1(&req)
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.SaveMediaProcess.Code, err, fmt.Sprintf("保存媒体处理失败， %s", err.Error()))
		return
	}

	e.OK(nil, "保存媒体处理成功")
}

func (e ChannelTask) GetMediaProcess(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.MediaProcessGetReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	data, err := s.GetMediaProcess(&req)
	if err != nil {
		e.Error(apis.DBQueryError.Code, err, fmt.Sprintf("获取媒体处理失败， %s", err.Error()))
		return
	}
	e.OK(data, "获取媒体处理成功")
}

func (e ChannelTask) RemoveMediaProcess(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.MediaProcessDeleteReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.RemoveMediaProcess(&req)
	if err != nil {
		e.Error(apis.DeleteMediaProcess.Code, err, fmt.Sprintf("删除媒体处理失败， %s", err.Error()))
		return
	}
	e.OK(req.Id, "删除媒体处理成功")
}

func (e ChannelTask) SaveTrafficOff(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.TrafficOffSaveReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.SaveTrafficOff1(&req)
	if err != nil {
		e.Error(apis.SaveTrafficOffError.Code, err, fmt.Sprintf("保存下车点失败， %s", err.Error()))
		return
	}
	info := dto.NodeInfo{
		Id:     req.Id,
		NodeId: req.NodeId,
	}
	e.OK(info, "保存下车点成功")
}

func (e ChannelTask) RemoveGetTrafficOff(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.TrafficOffDeleteReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.RemoveTrafficOff(&req)
	if err != nil {
		e.Error(apis.DeleteTrafficOnError.Code, err, fmt.Sprintf("删除下车点失败， %s", err.Error()))
		return
	}
	e.OK("", "删除成功")
}

func (e ChannelTask) GetTrafficOff(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.TrafficOffGetReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	data, err := s.GetTrafficOff(&req)
	if err != nil {
		e.Error(apis.DBQueryError.Code, err, fmt.Sprintf("获取下车点失败， %s", err.Error()))
		return
	}
	e.OK(data, "获取下车点成功")
}

func (e ChannelTask) SaveWorkflow(c *gin.Context) {
	s := &service.ChannelTaskService{}
	req := dto.SaveWorkflowReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	//获取通道基本信息
	var basic live_schedule.ChannelBasic
	e.Orm.Model(live_schedule.ChannelBasic{}).Where("tenant_id =? and id=?", req.TenantId, req.ChannelId).Find(&basic)
	////设置为执行中
	//param := make(map[string]interface{})
	//param["channel_state"] = 4
	//param["progress"] = "0"
	//err = e.Orm.Model(&live_schedule.ChannelBasic{}).Where("id=?", req.ChannelId).Updates(&param).Error
	//if err != nil {
	//	e.Error(apis.DBQueryError.Code, err, "更新通道配置失败")
	//	return
	//}
	err = s.SaveWorkflow(&req, basic)
	if err != nil {
		if err.Error() == string(apis.ScheduleCountError.Code) {
			e.Error(apis.ScheduleCountError.Code, err, fmt.Sprintf("保存通道配置失败， 通道分发数以超过限额"))
		} else {
			e.Error(apis.SaveWorkflowError.Code, err, fmt.Sprintf("保存通道配置失败， %s", err.Error()))
		}
		//param["channel_state"] = basic.ChannelState
		//err = e.Orm.Model(&live_schedule.ChannelBasic{}).Where("id=?", req.ChannelId).Updates(&param).Error
		//if err != nil {
		//	e.Error(apis.DBQueryError.Code, err, "更新通道配置失败")
		//	return
		//}
		return
	}

	e.OK(nil, "保存通道配置成功")
}

func (e ChannelTask) SaveWorkflow1(c *gin.Context) {
	s := &service.ChannelTaskService{}
	req := dto.SaveWorkflowReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	//获取通道基本信息
	var basic live_schedule.ChannelBasic
	e.Orm.Model(live_schedule.ChannelBasic{}).Where("tenant_id =? and id=?", req.TenantId, req.ChannelId).Find(&basic)
	////设置为执行中
	//param := make(map[string]interface{})
	//param["channel_state"] = 4
	//param["progress"] = "0"
	//err = e.Orm.Model(&live_schedule.ChannelBasic{}).Where("id=?", req.ChannelId).Updates(&param).Error
	//if err != nil {
	//	e.Error(apis.DBQueryError.Code, err, "更新通道配置失败")
	//	return
	//}
	err = s.SaveWorkflow1(&req, basic)
	if err != nil {
		if err.Error() == string(apis.ScheduleCountError.Code) {
			e.Error(apis.ScheduleCountError.Code, err, fmt.Sprintf("保存通道配置失败， 通道分发数以超过限额"))
		} else {
			e.Error(apis.SaveWorkflowError.Code, err, fmt.Sprintf("保存通道配置失败， %s", err.Error()))
		}
		//param["channel_state"] = basic.ChannelState
		//err = e.Orm.Model(&live_schedule.ChannelBasic{}).Where("id=?", req.ChannelId).Updates(&param).Error
		//if err != nil {
		//	e.Error(apis.DBQueryError.Code, err, "更新通道配置失败")
		//	return
		//}
		return
	}

	e.OK(nil, "保存通道配置成功")
}

func (e ChannelTask) GetWorkflow(c *gin.Context) {
	s := &service.ChannelTaskService{}
	req := dto.GetWorkflowReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	data, err := s.GetWorkflow(&req)
	if err != nil {
		e.Error(apis.DBQueryError.Code, err, fmt.Sprintf("获取通道配置失败， %s", err.Error()))
		return
	}
	e.OK(data, "获取通道配置成功")
}

func (e ChannelTask) StartOrStopNode(c *gin.Context) {
	s := &service.ChannelTaskService{}
	req := dto.StartOrStopNodeReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.StartOrStopNode(&req)
	if err != nil {
		e.Error(apis.DBQueryError.Code, err, fmt.Sprintf("启用或者停用节点失败， %s", err.Error()))
		return
	}
	e.OK(nil, "启用或者停用节点成功")
}

func (e ChannelTask) StartWorkflow(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.ProcessWorkflowReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.StartWorkflow(&req)
	if err != nil {
		e.Error(apis.StartWorkflowError.Code, err, fmt.Sprintf("开启通道置失败， %s", err.Error()))
		return
	}
	//c.Writer.Header().Set("Content-Length", "-1")
	e.OK(nil, "开启通道成功")
}

func (e ChannelTask) StopWorkflow(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.ProcessWorkflowReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.StopWorkflow(&req)
	if err != nil {
		e.Error(apis.StartWorkflowError.Code, err, fmt.Sprintf("停用通道置失败， %s", err.Error()))
		return
	}
	//c.Writer.Header().Set("Content-Length", "-1")
	e.OK("", "停用通道成功")
}

func (e ChannelTask) ConvertTaskCallBack(c *gin.Context) {
	s := service.ConvertTaskService{}
	req := dto.TargetCallBackReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	e.Logger.Trace("通道状态回调任务", req)
	err = s.ConvertTaskCallBack(&req)
	if err != nil {
		e.Error(apis.CallBackError.Code, err, fmt.Sprintf("回调接口失败， %s", err.Error()))
		return
	}
	e.OK("", "回调接口成功")
}

func (e ChannelTask) AuditTaskCallBack(c *gin.Context) {
	s := service.AuditTaskService{}
	req := dto.TargetCallBackReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	//e.Logger.Trace("审核回调任务", req)
	err = s.AuditTaskCallBack(&req)
	if err != nil {
		e.Error(apis.CallBackError.Code, err, fmt.Sprintf("回调接口失败， %s", err.Error()))
		return
	}
	e.OK("", "回调接口成功")
}

func (e ChannelTask) AuditPullTaskCallBack(c *gin.Context) {
	s := service.AuditTaskService{}
	req := dto.TargetCallBackReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	////e.Logger.Trace("审核拉流回调任务", req)
	//err = s.AuditPullTaskCallBack(&req)
	//if err != nil {
	//	e.Error(apis.CallBackError.Code, err, fmt.Sprintf("回调接口失败， %s", err.Error()))
	//	return
	//}
	e.OK("", "回调接口成功")
}

func (e ChannelTask) CortexTargetCallBack(c *gin.Context) {
	s := &service.CortexTaskService{}
	req := dto.TargetCallBackReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	e.Logger.Trace("软矩阵通道状态回调任务", req)
	err = s.CortexTargetCallBack(&req)
	if err != nil {
		e.Error(apis.CallBackError.Code, err, fmt.Sprintf("回调接口失败， %s", err.Error()))
		return
	}
	//c.Writer.Header().Set("Content-Length", "-1")
	e.OK("", "软矩阵通道状态回调接口成功")
}

func (e ChannelTask) GetScheduleStatistics(c *gin.Context) {
	s := service.ChannelStatisticsService{}
	req := dto.GetScheduleStatisticsReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}
	data, err := s.GetScheduleStatistics(&req)
	if err != nil {
		e.Error(apis.DBQueryError.Code, err, fmt.Sprintf("查询调度时间统计失败， %s", err.Error()))
		return
	}
	e.OK(data, "查询调度时间统计成功")
}

func (e ChannelTask) UpdateCortexOutput(c *gin.Context) {
	s := service.CortexTaskService{}
	req := dto.UpdateCortexOutput{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.UpdateCortexOutput(&req)
	if err != nil {
		if err.Error() == string(apis.OutPutNameRepeatError.Code) {
			e.Error(apis.OutPutNameRepeatError.Code, err, fmt.Sprintf("保存矩阵失败， %s", "矩阵输出名重复"))
		} else {
			e.Error(apis.UpdateCortexOutputError.Code, err, fmt.Sprintf("更新矩阵输出名失败， %s", err.Error()))
		}

		return
	}
	e.OK(nil, "更新矩阵输出名成功")
}

func (e ChannelTask) SaveCortex(c *gin.Context) {
	s := service.CortexTaskService{}
	req := dto.SaveCortexReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.SaveCortex(&req)
	if err != nil {
		if err.Error() == string(apis.OutPutNameRepeatError.Code) {
			e.Error(apis.OutPutNameRepeatError.Code, err, fmt.Sprintf("保存矩阵失败， %s", "矩阵输出名重复"))
		} else {
			e.Error(apis.SaveCortexError.Code, err, fmt.Sprintf("保存矩阵失败， %s", err.Error()))
		}
		return
	}
	e.OK(nil, "保存矩阵成功")
}

func (e ChannelTask) CreateCortexTask(c *gin.Context) {
	s := service.CortexTaskService{}
	req := dto.CreateCortexTaskReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			e.Logger.Error("Service CreateCortexTask error:%s \r\n", r)
			tx.Rollback()
			//return
		}
	}()
	if err = tx.Error; err != nil {
		e.Error(apis.InternalError.Code, err, err.Error())
	}
	err = s.CreateCortexTask(tx, &req)
	if err != nil {
		tx.Rollback()
		e.Error(apis.CreateCortexTaskError.Code, err, fmt.Sprintf("创建软矩阵任务失败， %s", err.Error()))
		return
	}
	tx.Commit()
	e.OK(nil, "创建软矩阵任务成功")
}

func (e ChannelTask) DeleteCortexTaskByOutputName(c *gin.Context) {
	s := service.CortexTaskService{}
	req := dto.DeleteCortexTaskReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.DeleteCortexTaskByOutputName(&req)
	if err != nil {
		e.Error(apis.DeleteCortexError.Code, err, fmt.Sprintf("删除软矩阵任务失败， %s", err.Error()))
		return
	}
	e.OK(nil, "删除软矩阵任务成功")
}

func (e ChannelTask) SwitchCortexSource(c *gin.Context) {
	s := service.CortexTaskService{}
	req := dto.SwitchCortexSourceReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.SwitchCortexSource(&req)
	if err != nil {
		e.Error(apis.CreateCortexTaskError.Code, err, fmt.Sprintf("切换软矩阵任务失败， %s", err.Error()))
		return
	}
	e.OK(nil, "切换软矩阵任务成功")
}

func (e ChannelTask) GetCortexTaskList(c *gin.Context) {
	s := service.CortexTaskService{}
	req := dto.GetCortexTaskListReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	data, err := s.GetCortexTaskList(&req)
	if err != nil {
		e.Error(apis.DBQueryError.Code, err, fmt.Sprintf("获取矩阵任务失败， %s", err.Error()))
		return
	}
	e.OK(data, "获取软矩阵任务成功")
}

func (e ChannelTask) GetCortexOutInfo(c *gin.Context) {
	s := service.CortexTaskService{}
	req := dto.GetCortexOutInfo{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	tx := e.Orm.Begin()
	data, err := s.GetCortexOutInfo(tx, &req)
	if err != nil {
		tx.Rollback()
		e.Error(apis.DBQueryError.Code, err, fmt.Sprintf("获取矩阵任务失败， %s", err.Error()))
		return
	}
	tx.Commit()
	e.OK(data, "获取软矩阵任务成功")
}

func (e ChannelTask) StartCortexTask(c *gin.Context) {
	s := service.CortexTaskService{}
	req := dto.StartCortexTaskReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.StartCortexTask(&req)
	if err != nil {
		e.Error(apis.StartCortexTaskError.Code, err, fmt.Sprintf("开启矩阵任务失败， %s", err.Error()))
		return
	}
	e.OK(nil, "开启软矩阵任务成功")
}

func (e ChannelTask) StopCortexTask(c *gin.Context) {
	s := service.CortexTaskService{}
	req := dto.StopCortexTaskReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.StopCortexTask(&req)
	if err != nil {
		e.Error(apis.StopSourceError.Code, err, fmt.Sprintf("停止矩阵任务失败， %s", err.Error()))
		return
	}
	e.OK(nil, "停止软矩阵任务成功")
}

func (e ChannelTask) GetCortexByFilter(c *gin.Context) {
	s := service.CortexTaskService{}
	req := dto.GetCortexReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	data, err := s.GetCortexByFilter(&req)
	if err != nil {
		e.Error(apis.StopSourceError.Code, err, fmt.Sprintf("搜索矩阵任务失败， %s", err.Error()))
		return
	}
	e.OK(data, "搜索软矩阵任务成功")
}

func (e ChannelTask) AuditCallBack(c *gin.Context) {
	s := service.AuditTaskService{}
	req := dto.AuditResult{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	e.Logger.Trace("进入审核结果回调任务", req)
	err = s.AuditResultCallBack(&req)
	if err != nil {
		e.Error(apis.StartCortexTaskError.Code, err, fmt.Sprintf("审核回调任务失败， %s", err.Error()))
		return
	}
	e.OK(nil, "审核回调成功")
}

func (e ChannelTask) AuditStatisticResult(c *gin.Context) {
	s := service.AuditTaskService{}
	req := dto.AuditStatisticReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	data, err := s.AuditStatisticResult(&req)
	if err != nil {
		e.Error(apis.StartCortexTaskError.Code, err, fmt.Sprintf("获取审核任务统计失败， %s", err.Error()))
		return
	}
	e.OK(data, "获取审核任务统计成功")
}

func (e ChannelTask) CheckUpUsed(c *gin.Context) {
	s := service.CortexTaskService{}
	req := dto.CheckUpUsedReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	data, err := s.CheckUpUsed(&req)
	if err != nil {
		e.Error(apis.DBQueryError.Code, err, fmt.Sprintf("查询山车点是否正在被使用失败， %s", err.Error()))
		return
	}
	if data > 0 {
		e.OK(apis.UpIsUsingError.Code, "查询山车点是否正在被使用成功")
	} else {
		e.OK(data, "查询山车点是否正在被使用成功")
	}
}

var clients = make(map[*websocket.Conn]bool)
var clientsMutex sync.Mutex

func (e ChannelTask) HandleWebSocket(c *gin.Context) {
	//s := service.ChannelTaskService{}
	//err := e.MakeContext(c).
	//	MakeOrm().
	//	MakeService(&s.Service).
	//	Errors
	//if err != nil {
	//	e.Logger.Error(err)
	//	e.Error(apis.InternalError.Code, err, err.Error())
	//	return
	//}

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Error("Failed to upgrade WebSocket connection:", err)
		return
	}
	defer conn.Close()

	// 将连接添加到客户端列表
	clientsMutex.Lock()
	clients[conn] = true
	c.Set("SocketClient", clients)
	clientsMutex.Unlock()

	for {
		// 读取客户端发送的消息
		_, msg, err := conn.ReadMessage()
		if err != nil {
			log.Error("Failed to read message:", err)
			break
		}

		log.Error("Received message:", string(msg))
	}
}

func (e ChannelTask) GetScheduleFlowStatistics(c *gin.Context) {
	s := service.ChannelStatisticsService{}
	req := dto.GetScheduleFlowReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}
	data, err := s.GetScheduleFlowStatistics(&req)
	if err != nil {
		e.Error(apis.DBQueryError.Code, err, fmt.Sprintf("查询调度用量统计失败， %s", err.Error()))
		return
	}
	e.OK(data, "查询调度用量统计成功")
}

func (e ChannelTask) StartOrStopTaskByTrafficOn(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.StopOrStopTaskByTrafficOnReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.StartOrStopTaskByTrafficOn(&req)
	if err != nil {
		if err.Error() == string(apis.UpStartError.Code) {
			e.Error(apis.UpStartError.Code, err, "通道未开启不能开启上车点")
		} else if err.Error() == string(apis.UpStartTimeError.Code) {
			e.Error(apis.UpStartTimeError.Code, err, "请稍后30秒之后重新开启")
		} else {
			e.Error(apis.EnableOrCancelTimeTaskError.Code, err, err.Error())
		}

		return
	}
	e.OK(nil, "停用或启用上车点任务成功")
}

func (e ChannelTask) StartOrStopTaskByTrafficOff(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.StopOrStopTaskByTrafficOffReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.StartOrStopTaskByTrafficOff(&req)
	if err != nil {
		if err.Error() == string(apis.UpStartTimeError.Code) {
			e.Error(apis.UpStartTimeError.Code, err, "请稍后30秒之后重新开启")
		} else {
			e.Error(apis.EnableOrCancelTimeTaskError.Code, err, err.Error())
		}
		return
	}
	e.OK(nil, "停用或启用下车点成功")
}

func (e ChannelTask) StartOrStopTaskByMediaProcess(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.StopOrStopTaskByMediaProcessReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.StartOrStopTaskByMediaProcess(&req)
	if err != nil {
		if err.Error() == string(apis.UpStartTimeError.Code) {
			e.Error(apis.UpStartTimeError.Code, err, "请稍后30秒之后重新开启")
		} else {
			e.Error(apis.EnableOrCancelTimeTaskError.Code, err, err.Error())
		}
		return
	}
	e.OK(nil, "停用或启用通到任务成功")
}

func (e ChannelTask) GetUpMedia(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.GetUpMediaReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	data, err := s.GetUpMedia(&req)
	if err != nil {
		e.Error(apis.EnableOrCancelTimeTaskError.Code, err, err.Error())
		return
	}
	e.OK(data, "获取媒体处理上车点成功")
}

func (e ChannelTask) TransCallBack(c *gin.Context) {
	req := dto.CallBackData{}
	s := service.ChannelTaskService{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}
	//e.Logger.Trace("回调转码任务：", req)
	err = s.TransCallBack(req)
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}
	e.OK(nil, "回调转码任务")
}

func (e ChannelTask) SwitchSource(c *gin.Context) {
	s := service.ChannelTaskService{}
	req := dto.SwitchSourceReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	err = s.SwitchSource(&req)
	if err != nil {
		e.Error(apis.DBQueryError.Code, err, fmt.Sprintf("切换源失败， %s", err.Error()))
		return
	}
	e.OK(nil, "切换源成功")
}
